# TODO: Dynamically grab version from gadget.xml
# TODO: Auto-increment build number

function Create-Zip($dir,$target){
	# TODO: Add exception handling
	$zip = ($env:programfiles)+'\7-Zip\7z.exe';
	Push-Location;
	Set-Location $dir;
	& $zip a -r -tzip $target .;
	Pop-Location;
}
function Get-Version($componentToIncrement){
	# get version
	$xml = Get-Content "$src\gadget.xml";
	$ver = New-Object System.Version(([xml]$xml).gadget.version);
	# update version
	$major = $ver.Major;
	$minor = $ver.Minor;
	$build = $ver.Build;
	$revision = $ver.Revision;
	if($componentToIncrement -eq 1){ $major = $major+1; $minor = $build = $revision = 0; }
	elseif($componentToIncrement -eq 2){ $minor = $minor+1; $build = $revision = 0; }
	elseif($componentToIncrement -eq 3){ $build = $build+1; $revision = 0; }
	else{ $revision = $revision+1; }
	$ver = New-Object System.Version($major, $minor, $build, $revision);
	$xml = $xml -replace '<version>[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+</version>', "<version>$ver</version>";
	Write-Output $xml | Out-File "$src\gadget.xml" -Encoding UTF8;
	return $ver;
}



# init vars
$src = 'src';
$proj = ([xml](Get-Content "$src\gadget.xml")).gadget.name.ToLower().Replace(' ','');
$ver = (Get-Version ($args[0]));
$rel = "$proj-$ver";
$target = (Get-Location).Path+"\$proj.gadget";

# start timer after getting version, since it includes manual intervention
$stopwatch = New-Object System.Diagnostics.StopWatch;
$stopwatch.Start();

# starting...
Write-Output "Packaging release $ver...";
Write-Output '';

# init
Write-Output "Removing previous build...";
Remove-Item $rel -errorAction SilentlyContinue;
Write-Output '';
Write-Output "Copying files..."
xcopy $src $rel\ /s /y;
Write-Output ''

# package
Write-Output "Creating gadget file...";
Create-Zip $rel $target;
Write-Output ''

# cleanup
Write-Output "Cleaning up...";
Remove-Item $rel -recurse;

# ...done
$stopwatch.Stop();
$elapsed = $stopwatch.Elapsed.TotalSeconds.ToString("#,###.00");
$time = [System.DateTime]::Now.ToString();
Write-Output "...completed @ $time ($elapsed seconds)";
Write-Output '';
